const db = uniCloud.database();
const dbcmd = db.command;

// 生成随机数
function generateRandomNDigitNumber(n) {
	// 生成一个 0 到 10^n - 1 之间的随机数
	const number = Math.floor(Math.random() * Math.pow(10, n));
	// 将数字转换为字符串，并在前面补 0 直到长度为 n
	return number.toString().padStart(n, '0');
}

module.exports = {
	_before: function() { // 通用预处理器

	},
	/** 获取数据库album列表，不包含歌曲信息
	 * @return {Array} albumList
	 */
	async GetAlbumList_e_albumList() {
		let res = await db.collection('albumList').field({
			'name': true,
			'number': true,
			'desc': true,
			'coverPath': true
		}).get();

		return {
			success: "success",
			message: "获取专辑列表成功",
			data: res.data
		}
	},
	/** 获取数据库album列表
	 * 
	 */
	async GetalbumList(user_id) {
		let res = await db.collection('albumList').where({
			user_id: user_id,
		}).get();

		return {
			success: "success",
			message: "获取专辑列表成功",
			data: res.data
		}
	},

	/**删除数据库album信息
	 * @param {string[] | string} albumList 专辑信息
	 * @returns {object} 返回值描述
	 */
	async deleteAlbum(albumList) {
		console.log('删除歌单', albumList);
		try {
			if (!albumList) {
				throw new Error('请求参数为空');
			}
			let albumIDList = [];
			let albumCoverPathList = [];
			if (Array.isArray(albumList)) {
				albumIDList = albumList.map(item => item._id);
				albumCoverPathList = albumList.map(item => item.coverPath);
			} else {
				albumIDList.push(albumList);
			}
			// 删除云存储封面文件
			const res_deleteFile = await uniCloud.deleteFile({
				fileList: albumCoverPathList
			});


			// 删除云数据库记录
			let p = []
			albumIDList.forEach((item, index) => {
				p[index] = new Promise((resolve, reject) => {
					db.collection('albumList').where({
						_id: item
					}).remove().then(res => {
						resolve(res);
					});
				});
			});

			const res = await Promise.all(p)

			return {
				code: 0,
				message: '专辑删除成功',
				res: res,
			};

		} catch (error) {
			return {
				code: 1,
				message: '专辑删除失败',
				error: error.message
			};
		}
	},
	/**搜索专辑信息
	 * 
	 */
	async searchAlbums(albumInfo) {
		try {
			let {
				name
			} = albumInfo;
			res = await db.collection('albumList').where({
				name: new RegExp(name),
			}).get();
			return {
				code: 0,
				message: '歌单搜索成功',
				data: res
			};
		} catch (error) {
			return {
				code: 1,
				message: '歌单搜索失败',
				error: error.message
			};
		}
	},

	/**更新专辑信息 无法更新musicList!!!
	 * @param {Object} albumInfo
	 * @param {String} albumInfo._id
	 * @param {String} albumInfo._name
	 * @param {String} albumInfo._desc
	 * @param {String} albumInfo._coverPath
	 */
	async updateAlbumInfo(albumInfo) {
		try {
			console.log(albumInfo);
			let {
				_id,
				name,
				desc,
				coverPath
			} = albumInfo;
			let res = await db.collection('albumList').where({
				_id: _id,
			}).update({
				name: name,
				desc: desc,
				coverPath: coverPath,
			});
			return {
				message: '更新专辑信息成功',
				res: res,
			}
		} catch (err) {
			return {
				message: '更新专辑信息失败',
				err: err,
			}
		}
	},
	// 删除 数据库album musicList
	async deleteAlbumMusicList(albumInfo) {
		try {
			console.log(albumInfo);
			let {
				_id,
				musicList,
				minusNumber
			} = albumInfo;
			let res = await db.collection('albumList').where({
				_id: _id,
			}).update({
				number: dbcmd.inc(-minusNumber),
				musicList: musicList,
			});
			return {
				message: '更新专辑音乐列表成功',
				res: res,
			}
		} catch (err) {
			return {
				message: '更新专辑音乐列表失败',
				err: err,
			}
		}
	},
	/**特定专辑 添加一首歌
	 * @param {Object} albumInfo
	 * @param {String} albumInfo._id
	 * @param {Array} albumInfo.musicList
	 */
	async PushBack_one_publicAlbum(albumID, element) {
		let res = await db.collection('albumList').where({
			_id: albumID,
		}).update({
			number: dbcmd.inc(1),
			musicList: dbcmd.push(element),
		});

		return {
			code: '0',
			message: '新增专辑音乐列表成功',
			res: res,
		}
	},
	/**特定专辑 添加多首歌
	 * @param {Object} albumID
	 * @param {Object} element
	 */
	async PushBack_all_publicAlbum(albumID, elements) {
		const length = elements.length;
		let res = await db.collection('albumList').where({
			_id: albumID,
		}).update({
			number: dbcmd.inc(length),
			musicList: dbcmd.push(elements),
		});

		return {
			code: '0',
			message: '新增专辑音乐列表成功',
			res: res,
		}
	},


	/**创建数据库album信息
	 * @param {Object} albumInfo - 专辑信息
	 * @param {string} albumInfo.name - 专辑名字
	 * @param {string} albumInfo.desc - 专辑描述
	 */
	async CreateAlbum(personalAlbum) {
		const {
			name,
			private,
			user_id,
		} = personalAlbum;


		const avatar_cloudpath_default =
			'https://mp-a52cf949-e385-4e78-b2b7-81a8dd621c31.cdn.bspapp.com/cloud/album/cover_default/cover_default_';
		const avatar_cloudPath =
			avatar_cloudpath_default + generateRandomNDigitNumber(1) + ".jpg";

		let res = await db.collection('albumList').add({
			name: name,
			user_id: user_id,
			private: private,
			desc: '',
			number: 0,
			musicList: [],
			coverPath: avatar_cloudPath,
			upLoadTime: new Date().getTime(),

		});

		return {
			success: true,
			message: '新增个人专辑成功',
		}
	},
	/** 获取album信息 单个
	 * @param {string} albumID - 专辑ID
	 */
	async GetAlbumInfo(albumID) {
		if (!albumID) {
			return {
				success: "fail",
				message: "参数有误",
			};
		}

		let res = await db.collection('albumList').where({
			_id: albumID,
		}).get();

		return {
			success: "success",
			message: "获取专辑信息成功",
			data: res.data[0],
		};
	},
	/**特定专辑 添加一首歌
	 * @param {Object} albumID
	 * @param {Object} element
	 */
	async PushBack_one_personalAlbum(albumID, element) {
		if (!(albumID && element)) {
			return {
				success: "fail",
				message: '传入参数有误',
			}
		}

		// 检查是否已有
		let res_get = await db.collection('albumList').where({
			_id: albumID,
		}).get();
		const musicList_old = res_get.data[0].musicList;
		console.log(musicList_old);
		if (musicList_old.length >= 1) {
			for (let i = 0; i < musicList_old.length; i++) {
				let musicID = musicList_old[i];
				console.log(musicID);
				if (musicID == element) {
					return {
						success: "fail",
						message: '专辑音乐列表已有该音乐',
					}
				}
			}
		}

		// 插入新的
		let res_update = await db.collection('albumList').where({
			_id: albumID,
		}).update({
			number: dbcmd.inc(1),
			musicList: dbcmd.push(element),
		});

		return {
			success: "success",
			message: '新增专辑音乐列表成功',
			res: res_update,
		}
	},

}